package cn.flying.cloud.core.auth.session;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;

import cn.flying.cloud.base.common.enums.RtCodeEnum;
import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.base.common.vo.Rt;
import cn.flying.cloud.core.auth.details.UserDetail;
import cn.flying.cloud.system.common.service.UserService;
import cn.flying.cloud.system.log.entity.SysLoginLog;

/**
 * @description: 登录踢下线后的处理策略
 * @author: admin
 * @date: 2023年05月26日 00:49
 * @version: 1.0
 */
@Component
public class SessionExpiredStrategy implements SessionInformationExpiredStrategy {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserService userService;

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
        Object principal = event.getSessionInformation().getPrincipal();
        HttpServletRequest request = event.getRequest();
        HttpServletResponse response = event.getResponse();

        UserDetail userDetail = (UserDetail) principal;
        logger.info("租户【{}】的用户【{}-{}】在其他地方登录，被强制踢下线", userDetail.getTenantId(), userDetail.getUserId(), userDetail.getUsername());

        try {
            //保存登录日志
            SysLoginLog log = new SysLoginLog();
            log.setUserId(userDetail.getUserId());
            log.setUserName(userDetail.getUsername());
            log.setName(userDetail.getName());
            log.setHappenType("会话失效");
            log.setHappenTime(LocalDateTime.now());
            log.setHappenIp(Ft.Network.getIpAddress(request));
            log.setRemark("同一个账户多终端登录，强制下线");
            log.setTenantId(userDetail.getTenantId());
            log.setCreatedBy(userDetail.getUsername());
            log.setCreatedTime(LocalDateTime.now());
            log.setUpdatedBy(userDetail.getUsername());
            log.setUpdatedTime(LocalDateTime.now());
            log.setRevision(0L);
            userService.insertLoginLog(log);
        } catch (Exception e) {
            logger.warn("系统登录日志保存失败，异常原因【{}】", e.getMessage());
        }

        //判断请求类型，根据不同的类型返回
        String xmlHttpRequest = "XMLHttpRequest";
        String requestedWith = request.getHeader("x-requested-with");
        if (requestedWith != null && requestedWith.equalsIgnoreCase(xmlHttpRequest)) {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(Rt.error(RtCodeEnum.R10018)));
            out.flush();
            out.close();
        } else {
            //访问页面的直接跳转到登录页面
            new DefaultRedirectStrategy().sendRedirect(request, response, "/auth/login/page");
            //这里采用转发的方式，因为重定向后浏览器的地址变了
//            request.getRequestDispatcher("/auth/login/page").forward(request, response);
        }
    }
}
